#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTabWidget>
#include "assign_group_dialog.h"
#include <QStackedWidget>
#include <QTableWidget>
#include <QPushButton>
#include <QFile>
#include <QTextStream>
#include <QTableWidgetItem>
#include "select_teacher_dialog.h"
#include <QHBoxLayout>
#include "upload_file_dialog.h"
#include "evaluate_dialog.h"
#include "login_dialog.h"
#include "teacher_comment_dialog.h"
#include "supervisor_comment_dialog.h"
#include "student_submit_dialog.h"
#include "view_project_dialog.h"
#include "score_summary_dialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 分配课设小组按钮切换到表格页
    QPushButton* btnAssignGroup = findChild<QPushButton*>("btn_assign_group");
    QStackedWidget* stackedWidget = findChild<QStackedWidget*>("stackedWidget");
    QWidget* pageAssignGroup = findChild<QWidget*>("page_assign_group");
    QTableWidget* tableWidgetAssignGroup = findChild<QTableWidget*>("tableWidget_assign_group");
    QPushButton* btnBackAssignGroup = findChild<QPushButton*>("btn_back_assign_group");
    if (btnAssignGroup && stackedWidget && pageAssignGroup && tableWidgetAssignGroup && btnBackAssignGroup) {
        connect(btnAssignGroup, &QPushButton::clicked, this, [=]() {
            // 加载学生数据
            tableWidgetAssignGroup->setRowCount(0);
            tableWidgetAssignGroup->setColumnCount(4);
            tableWidgetAssignGroup->setHorizontalHeaderLabels(QStringList() << "姓名" << "班级" << "已分配老师" << "操作");
            QFile file("students.txt");
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&file);
                int row = 0;
                while (!in.atEnd()) {
                    QString line = in.readLine().trimmed();
                    if (line.isEmpty()) continue;
                    QStringList parts = line.split(",");
                    if (parts.size() >= 2) {
                        tableWidgetAssignGroup->insertRow(row);
                        tableWidgetAssignGroup->setItem(row, 0, new QTableWidgetItem(parts[0].trimmed()));
                        tableWidgetAssignGroup->setItem(row, 1, new QTableWidgetItem(parts[1].trimmed()));
                        QString teacher = (parts.size() >= 3) ? parts[2].trimmed() : "";
                        QTableWidgetItem *item = new QTableWidgetItem(teacher);
                        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
                        tableWidgetAssignGroup->setItem(row, 2, item);
                        QPushButton *btnAssignTeacher = new QPushButton("分配老师");
                        tableWidgetAssignGroup->setCellWidget(row, 3, btnAssignTeacher);
                        connect(btnAssignTeacher, &QPushButton::clicked, this, [=]() {
                            // 读取老师列表
                            QStringList teachers;
                            QFile tfile("teachers.txt");
                            if (tfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
                                QTextStream tin(&tfile);
                                while (!tin.atEnd()) {
                                    QString tname = tin.readLine().trimmed();
                                    if (!tname.isEmpty()) teachers << tname;
                                }
                            }
                            SelectTeacherDialog dlg(teachers, this);
                            if (dlg.exec() == QDialog::Accepted) {
                                QString selected = dlg.selectedTeacher();
                                QTableWidgetItem *item = new QTableWidgetItem(selected);
                                item->setFlags(item->flags() & ~Qt::ItemIsEditable);
                                tableWidgetAssignGroup->setItem(row, 2, item);
                                QFile rf("students.txt");
                                QStringList allLines;
                                if (rf.open(QIODevice::ReadOnly | QIODevice::Text)) {
                                    QTextStream rin(&rf);
                                    while (!rin.atEnd()) allLines << rin.readLine();
                                    rf.close();
                                }
                                int idx = row;
                                if (idx >= 0 && idx < allLines.size()) {
                                    QStringList parts = allLines[idx].split(",");
                                    if (parts.size() >= 2) {
                                        QString score = (parts.size() >= 4) ? parts[3].trimmed() : "";
                                        allLines[idx] = parts[0].trimmed() + "," + parts[1].trimmed() + "," + selected + (score.isEmpty() ? "" : ("," + score));
                                    }
                                }
                                QFile wf("students.txt");
                                if (wf.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
                                    QTextStream wout(&wf);
                                    for (const QString &l : allLines) wout << l.trimmed() << "\n";
                                }
                            }
                        });
                        row++;
                    }
                }
            }
            stackedWidget->setCurrentWidget(pageAssignGroup);
        });
        // 返回按钮切回主界面
        connect(btnBackAssignGroup, &QPushButton::clicked, this, [=]() {
            stackedWidget->setCurrentIndex(0);
        });
    }

    QPushButton* btnViewGroupAssign = findChild<QPushButton*>("btn_view_group_assign");
    QWidget* pageViewGroupAssign = findChild<QWidget*>("page_view_group_assign");
    QTableWidget* tableWidgetViewGroupAssign = findChild<QTableWidget*>("tableWidget_view_group_assign");
    QPushButton* btnBackViewGroupAssign = findChild<QPushButton*>("btn_back_view_group_assign");
    if (btnViewGroupAssign && stackedWidget && pageViewGroupAssign && tableWidgetViewGroupAssign && btnBackViewGroupAssign) {
        connect(btnViewGroupAssign, &QPushButton::clicked, this, [=]() {
            tableWidgetViewGroupAssign->setRowCount(0);
            tableWidgetViewGroupAssign->setColumnCount(3);
            tableWidgetViewGroupAssign->setHorizontalHeaderLabels(QStringList() << "姓名" << "班级" << "已分配老师");
            QFile file("students.txt");
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&file);
                int row = 0;
                while (!in.atEnd()) {
                    QString line = in.readLine().trimmed();
                    if (line.isEmpty()) continue;
                    QStringList parts = line.split(",");
                    if (parts.size() >= 2) {
                        tableWidgetViewGroupAssign->insertRow(row);
                        QTableWidgetItem *item0 = new QTableWidgetItem(parts[0].trimmed());
                        QTableWidgetItem *item1 = new QTableWidgetItem(parts[1].trimmed());
                        QString teacher = (parts.size() >= 3) ? parts[2].trimmed() : "";
                        QTableWidgetItem *item2 = new QTableWidgetItem(teacher);
                        item0->setFlags(item0->flags() & ~Qt::ItemIsEditable);
                        item1->setFlags(item1->flags() & ~Qt::ItemIsEditable);
                        item2->setFlags(item2->flags() & ~Qt::ItemIsEditable);
                        tableWidgetViewGroupAssign->setItem(row, 0, item0);
                        tableWidgetViewGroupAssign->setItem(row, 1, item1);
                        tableWidgetViewGroupAssign->setItem(row, 2, item2);
                        row++;
                    }
                }
            }
            stackedWidget->setCurrentWidget(pageViewGroupAssign);
        });
        connect(btnBackViewGroupAssign, &QPushButton::clicked, this, [=]() {
            stackedWidget->setCurrentIndex(0);
        });
    }

    QPushButton* btnUploadFile = findChild<QPushButton*>("btn_upload_file");
    if (btnUploadFile) {
        connect(btnUploadFile, &QPushButton::clicked, this, [=]() {
            UploadFileDialog dlg(this);
            dlg.exec();
        });
    }

    QPushButton* btnViewList = findChild<QPushButton*>("btn_view_list");
    if (btnViewList) {
        connect(btnViewList, &QPushButton::clicked, this, [=]() {
            EvaluateDialog dlg(this);
            dlg.exec();
        });
    }

    QPushButton* btnSubmitTeacherStudent = findChild<QPushButton*>("btn_submit_teacher_student");
    if (btnSubmitTeacherStudent) {
        connect(btnSubmitTeacherStudent, &QPushButton::clicked, this, [=]() {
            UploadFileDialog dlg(this);
            dlg.exec();
        });
    }
    QPushButton* btnAssignTopic = findChild<QPushButton*>("btn_assign_topic");
    if (btnAssignTopic) {
        connect(btnAssignTopic, &QPushButton::clicked, this, [=]() {
            UploadFileDialog dlg(this);
            dlg.exec();
        });
    }
    QPushButton* btnSubmitProject = findChild<QPushButton*>("btn_submit_project");
    if (btnSubmitProject) {
        connect(btnSubmitProject, &QPushButton::clicked, this, [=]() {
            StudentSubmitDialog dlg(currentAccount, this);
            dlg.exec();
        });
    }

    QPushButton* btnViewScore = findChild<QPushButton*>("btn_view_score");
    if (btnViewScore) {
        connect(btnViewScore, &QPushButton::clicked, this, [=]() {
            EvaluateDialog dlg(this, true);
            dlg.exec();
        });
    }

    QPushButton* btnEvaluate = findChild<QPushButton*>("btn_evaluate");
    if (btnEvaluate) {
        connect(btnEvaluate, &QPushButton::clicked, this, [=]() {
            TeacherCommentDialog dlg(this);
            dlg.exec();
        });
    }

    QPushButton* btnGiveEvaluation = findChild<QPushButton*>("btn_give_evaluation");
    if (btnGiveEvaluation) {
        connect(btnGiveEvaluation, &QPushButton::clicked, this, [=]() {
            SupervisorCommentDialog dlg(this);
            dlg.exec();
        });
    }

    QPushButton* btnViewProjectTeacher = findChild<QPushButton*>("btn_view_info");
    if (btnViewProjectTeacher) {
        connect(btnViewProjectTeacher, &QPushButton::clicked, this, [=]() {
            ViewProjectDialog dlg(this);
            dlg.exec();
        });
    }
    QPushButton* btnViewProjectSupervisor = findChild<QPushButton*>("btn_view_project");
    if (btnViewProjectSupervisor) {
        connect(btnViewProjectSupervisor, &QPushButton::clicked, this, [=]() {
            ViewProjectDialog dlg(this);
            dlg.exec();
        });
    }

    QPushButton* btnSaveScore = findChild<QPushButton*>("btn_save_score");
    if (btnSaveScore) {
        connect(btnSaveScore, &QPushButton::clicked, this, [=]() {
            ScoreSummaryDialog dlg(this);
            dlg.exec();
        });
    }

    auto relogin = [this]() {
        this->close();
        // 重新弹出登录对话框
        LoginDialog loginDialog;
        if (loginDialog.exec() == QDialog::Accepted) {
            MainWindow *w = new MainWindow();
            w->setAttribute(Qt::WA_DeleteOnClose);
            w->setUserRole(static_cast<MainWindow::UserRole>(loginDialog.getSelectedRole()));
            w->show();
        }
    };
    QPushButton* btnBackLoginLeader = findChild<QPushButton*>("btn_back_login_leader");
    if (btnBackLoginLeader) connect(btnBackLoginLeader, &QPushButton::clicked, this, relogin);
    QPushButton* btnBackLoginAdmin = findChild<QPushButton*>("btn_back_login_admin");
    if (btnBackLoginAdmin) connect(btnBackLoginAdmin, &QPushButton::clicked, this, relogin);
    QPushButton* btnBackLoginTeacher = findChild<QPushButton*>("btn_back_login_teacher");
    if (btnBackLoginTeacher) connect(btnBackLoginTeacher, &QPushButton::clicked, this, relogin);
    QPushButton* btnBackLoginStudent = findChild<QPushButton*>("btn_back_login_student");
    if (btnBackLoginStudent) connect(btnBackLoginStudent, &QPushButton::clicked, this, relogin);
    QPushButton* btnBackLoginSupervisor = findChild<QPushButton*>("btn_back_login_counselor");
    if (btnBackLoginSupervisor) connect(btnBackLoginSupervisor, &QPushButton::clicked, this, relogin);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setUserRole(UserRole role)
{
    currentRole = role;
    QTabWidget* tabWidget = findChild<QTabWidget*>("tabWidget");
    if (!tabWidget) return;
    // 只保留当前身份的标签页，移除其他标签页
    for (int i = tabWidget->count() - 1; i >= 0; --i) {
        if (i != static_cast<int>(role)) {
            QWidget* w = tabWidget->widget(i);
            tabWidget->removeTab(i);
            delete w;
        }
    }
    tabWidget->setCurrentIndex(0);
}

void MainWindow::setUserAccount(const QString &account)
{
    currentAccount = account;
}
